package com.leadingsoft.common.utils;

public class IDUtil {
	private long workerId;
	private final static long twepoch = 1234567888888L;
	private long sequence = 0L;
	private long lastTimestamp = -1L;
	private final static long workerIdBits = 4L;
	private final static long sequenceBits = 10L;
	private final static long workerIdShift = sequenceBits;
	private final static long timestampLeftShift = sequenceBits + workerIdBits;
	public final static long sequenceMask = -1L ^ -1L << sequenceBits;
	public final static long maxWorkerId = -1L ^ -1L << workerIdBits;

	/**
	 * 构造方法
	 * @param workerId 机器ID 一个App一个机器ID
	 */
	public IDUtil(final long workerId) {
		super();
		// 机器ID超过了设置的最大ID数
		if (workerId > IDUtil.maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(
					String.format("worker Id can't be greater than %d or less than 0", IDUtil.maxWorkerId));
		}
		this.workerId = workerId;
	}
	/**
	 * 构造方法
	 * @param workerId 机器ID 一个App一个机器ID
	 */
	public IDUtil() {
		super();
		// 机器ID超过了设置的最大ID数
		if (workerId > IDUtil.maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(
					String.format("worker Id can't be greater than %d or less than 0", IDUtil.maxWorkerId));
		}
		this.workerId = 8L;
	}
	/**
	 * 获取ID
	 * @return ID
	 */
	public synchronized long nextId() {
		long timestamp = this.timeGen();
		if (this.lastTimestamp == timestamp) {
			this.sequence = (this.sequence + 1) & IDUtil.sequenceMask;
			if (this.sequence == 0) {
				timestamp = this.tilNextMillis(this.lastTimestamp);
			}
		} else {
			this.sequence = 0;
		}
		// 系统时间出现问题
		if (timestamp < this.lastTimestamp) {
			try {
				throw new Exception(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
						this.lastTimestamp - timestamp));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		this.lastTimestamp = timestamp;
		long nextId = ((timestamp - twepoch) << timestampLeftShift) | (this.workerId << IDUtil.workerIdShift)
				| (this.sequence);
		return nextId;
	}
	/**
	 * 判断毫秒
	 * @param lastTimestamp 生成上一个ID的时候的毫秒数
	 * @return 毫秒数
	 */
	private long tilNextMillis(final long lastTimestamp) {
		long timestamp = this.timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = this.timeGen();
		}
		return timestamp;
	}
	/**
	 * 获取当前系统的毫秒数
	 * @return 系统当前毫秒数
	 */
	private long timeGen() {
		return System.currentTimeMillis();
	}
	public static void main(String[] args) {
		IDUtil idUtil = new IDUtil();
		System.out.println(idUtil.nextId());
	}
}
